import React, { useState, useEffect } from 'react';
import {
  Card,
  Table,
  Button,
  Input,
  Select,
  Space,
  Tag,
  Avatar,
  Modal,
  message,
  Row,
  Col,
  Statistic,
  Typography,
  Tabs,
  Form,
  DatePicker,
  Tooltip,
  Badge,
  Descriptions,
  Timeline,
  Divider
} from 'antd';
import type { ColumnsType, TableProps } from 'antd/es/table';
import {
  SearchOutlined,
  CheckOutlined,
  CloseOutlined,
  EyeOutlined,
  HistoryOutlined,
  FilterOutlined,
  ExportOutlined,
  AppstoreOutlined
} from '@ant-design/icons';
import { useAppDispatch } from '../../store';
import { setBreadcrumbs } from '../../store/slices/uiSlice';
import { ShopService } from '../../services/shopService';
import { Shop } from '../../types';
import dayjs from 'dayjs';

const { Title, Text } = Typography;
const { TabPane } = Tabs;
const { RangePicker } = DatePicker;
const { TextArea } = Input;

interface ApprovalRecord {
  id: string;
  shopId: string;
  shopName: string;
  action: 'approved' | 'rejected' | 'suspended' | 'resumed';
  reason?: string;
  operator: string;
  operatorId: string;
  createdAt: string;
  previousStatus: string;
  newStatus: string;
}

interface ShopApprovalState {
  // 待审核商店
  pendingShops: Shop[];
  pendingLoading: boolean;
  pendingTotal: number;
  pendingCurrent: number;
  pendingPageSize: number;

  // 审核历史
  approvalHistory: ApprovalRecord[];
  historyLoading: boolean;
  historyTotal: number;
  historyCurrent: number;
  historyPageSize: number;

  // 筛选条件
  keyword: string;
  dateRange: [dayjs.Dayjs, dayjs.Dayjs] | null;
  actionFilter: string;

  // 选中的商店
  selectedRowKeys: React.Key[];

  // 模态框
  batchModalVisible: boolean;
  detailModalVisible: boolean;
  selectedShop: Shop | null;
}

const ShopApproval: React.FC = () => {
  const dispatch = useAppDispatch();
  const [form] = Form.useForm();

  const [state, setState] = useState<ShopApprovalState>({
    pendingShops: [],
    pendingLoading: false,
    pendingTotal: 0,
    pendingCurrent: 1,
    pendingPageSize: 10,

    approvalHistory: [],
    historyLoading: false,
    historyTotal: 0,
    historyCurrent: 1,
    historyPageSize: 10,

    keyword: '',
    dateRange: null,
    actionFilter: '',

    selectedRowKeys: [],

    batchModalVisible: false,
    detailModalVisible: false,
    selectedShop: null,
  });

  useEffect(() => {
    dispatch(setBreadcrumbs([
      { title: '首页', path: '/' },
      { title: '商店管理', path: '/shops' },
      { title: '商店审核' },
    ]));

    loadPendingShops();
    loadApprovalHistory();
  }, [dispatch]);

  // 加载待审核商店
  const loadPendingShops = async (params?: Partial<ShopApprovalState>) => {
    try {
      setState(prev => ({ ...prev, pendingLoading: true }));

      const queryParams = {
        page: params?.pendingCurrent || state.pendingCurrent,
        limit: params?.pendingPageSize || state.pendingPageSize,
        status: 'pending',
        keyword: params?.keyword || state.keyword,
      };

      const response = await ShopService.getPendingShops(queryParams);

      setState(prev => ({
        ...prev,
        pendingShops: response.data || [],
        pendingTotal: response.total || 0,
        pendingCurrent: response.pagination?.current || 1,
        pendingPageSize: response.pagination?.pageSize || 10,
        pendingLoading: false,
      }));
    } catch (error) {
      console.error('加载待审核商店失败:', error);
      message.error('加载待审核商店失败');
      setState(prev => ({ ...prev, pendingLoading: false }));
    }
  };

  // 加载审核历史
  const loadApprovalHistory = async (params?: Partial<ShopApprovalState>) => {
    try {
      setState(prev => ({ ...prev, historyLoading: true }));

      const queryParams = {
        page: params?.historyCurrent || state.historyCurrent,
        limit: params?.historyPageSize || state.historyPageSize,
        keyword: params?.keyword || state.keyword,
        action: params?.actionFilter || state.actionFilter,
        startDate: state.dateRange?.[0]?.format('YYYY-MM-DD'),
        endDate: state.dateRange?.[1]?.format('YYYY-MM-DD'),
      };

      // 这里需要后端提供审核历史接口
      const response = await ShopService.getApprovalHistory(queryParams);

      setState(prev => ({
        ...prev,
        approvalHistory: response.data || [],
        historyTotal: response.total || 0,
        historyCurrent: response.pagination?.current || 1,
        historyPageSize: response.pagination?.pageSize || 10,
        historyLoading: false,
      }));
    } catch (error) {
      console.error('加载审核历史失败:', error);
      message.error('加载审核历史失败');
      setState(prev => ({ ...prev, historyLoading: false }));
    }
  };

  // 单个审核
  const handleSingleApproval = async (shopId: string, action: 'approved' | 'rejected', reason?: string) => {
    try {
      await ShopService.approveShop(shopId, {
        status: action,
        reason: action === 'rejected' ? reason : undefined
      });

      message.success(`商店${action === 'approved' ? '审核通过' : '审核拒绝'}`);
      loadPendingShops();
      loadApprovalHistory();
    } catch (error) {
      message.error('审核失败');
    }
  };

  // 批量审核
  const handleBatchApproval = async (action: 'approved' | 'rejected', reason?: string) => {
    if (state.selectedRowKeys.length === 0) {
      message.warning('请选择要审核的商店');
      return;
    }

    try {
      const ids = state.selectedRowKeys.map(key => key.toString());
      await ShopService.batchActionShops(ids, action, reason);

      message.success(`成功${action === 'approved' ? '通过' : '拒绝'} ${ids.length} 个商店`);
      loadPendingShops();
      loadApprovalHistory();
      setState(prev => ({
        ...prev,
        selectedRowKeys: [],
        batchModalVisible: false
      }));
    } catch (error) {
      message.error('批量审核失败');
    }
  };

  // 查看商店详情
  const handleViewDetail = (shop: Shop) => {
    setState(prev => ({
      ...prev,
      selectedShop: shop,
      detailModalVisible: true,
    }));
  };

  // 获取状态标签
  const getStatusTag = (status: string) => {
    const statusMap = {
      pending: { color: 'orange', text: '待审核' },
      active: { color: 'green', text: '正常营业' },
      rejected: { color: 'red', text: '审核拒绝' },
      suspended: { color: 'red', text: '已暂停' },
    };
    const config = statusMap[status as keyof typeof statusMap] || { color: 'default', text: status };
    return <Tag color={config.color}>{config.text}</Tag>;
  };

  // 获取操作标签
  const getActionTag = (action: string) => {
    const actionMap = {
      approved: { color: 'green', text: '审核通过' },
      rejected: { color: 'red', text: '审核拒绝' },
      suspended: { color: 'orange', text: '暂停营业' },
      resumed: { color: 'blue', text: '恢复营业' },
    };
    const config = actionMap[action as keyof typeof actionMap] || { color: 'default', text: action };
    return <Tag color={config.color}>{config.text}</Tag>;
  };

  // 待审核商店表格列
  const pendingColumns: ColumnsType<Shop> = [
    {
      title: '商店信息',
      key: 'info',
      width: 300,
      render: (_, record) => (
        <div style={{ display: 'flex', alignItems: 'center' }}>
          <Avatar src={record.logo} size={48} style={{ marginRight: 12 }} />
          <div>
            <div style={{ fontWeight: 'bold', marginBottom: 4 }}>{record.name}</div>
            <div style={{ color: '#666', fontSize: '12px' }}>
              店主: {record.owner?.name || 'N/A'}
            </div>
            <div style={{ color: '#666', fontSize: '12px' }}>
              申请时间: {dayjs(record.createdAt).format('YYYY-MM-DD HH:mm')}
            </div>
          </div>
        </div>
      ),
    },
    {
      title: '商店类型',
      dataIndex: 'type',
      key: 'type',
      width: 100,
      render: (type) => {
        const typeMap = {
          official: '官方旗舰店',
          flagship: '品牌旗舰店',
          authorized: '授权专营店',
          personal: '个人店铺',
        };
        return typeMap[type as keyof typeof typeMap] || type;
      },
    },
    {
      title: '分类',
      dataIndex: 'categories',
      key: 'categories',
      width: 150,
      render: (categories) => categories?.join(', ') || 'N/A',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status) => getStatusTag(status),
    },
    {
      title: '操作',
      key: 'actions',
      width: 200,
      render: (_, record) => (
        <Space size="small">
          <Tooltip title="查看详情">
            <Button
              type="text"
              icon={<EyeOutlined />}
              onClick={() => handleViewDetail(record)}
            />
          </Tooltip>
          <Tooltip title="审核通过">
            <Button
              type="text"
              icon={<CheckOutlined />}
              style={{ color: 'green' }}
              onClick={() => handleSingleApproval(record._id, 'approved')}
            />
          </Tooltip>
          <Tooltip title="审核拒绝">
            <Button
              type="text"
              icon={<CloseOutlined />}
              style={{ color: 'red' }}
              onClick={() => {
                Modal.confirm({
                  title: '审核拒绝',
                  content: (
                    <Form>
                      <Form.Item label="拒绝原因" name="reason">
                        <TextArea rows={3} placeholder="请输入拒绝原因" />
                      </Form.Item>
                    </Form>
                  ),
                  onOk: (close) => {
                    const reason = form.getFieldValue('reason');
                    handleSingleApproval(record._id, 'rejected', reason);
                    close();
                  },
                });
              }}
            />
          </Tooltip>
        </Space>
      ),
    },
  ];

  return (
    <div>
      <Title level={2}>商店审核管理</Title>

      <Tabs defaultActiveKey="pending">
        <TabPane tab={<span><AppstoreOutlined />待审核商店</span>} key="pending">
          {/* 统计卡片 */}
          <Row gutter={16} style={{ marginBottom: 16 }}>
            <Col span={8}>
              <Card>
                <Statistic
                  title="待审核商店"
                  value={state.pendingTotal}
                  valueStyle={{ color: '#faad14' }}
                />
              </Card>
            </Col>
            <Col span={8}>
              <Card>
                <Statistic
                  title="今日新申请"
                  value={state.pendingShops.filter(shop =>
                    dayjs(shop.createdAt).isAfter(dayjs().startOf('day'))
                  ).length}
                  valueStyle={{ color: '#1890ff' }}
                />
              </Card>
            </Col>
            <Col span={8}>
              <Card>
                <Statistic
                  title="已选中"
                  value={state.selectedRowKeys.length}
                  valueStyle={{ color: '#52c41a' }}
                />
              </Card>
            </Col>
          </Row>

          {/* 操作栏 */}
          <Card style={{ marginBottom: 16 }}>
            <Row gutter={16} align="middle">
              <Col flex="auto">
                <Space>
                  <Input
                    placeholder="搜索商店名称或店主"
                    prefix={<SearchOutlined />}
                    value={state.keyword}
                    onChange={(e) => setState(prev => ({ ...prev, keyword: e.target.value }))}
                    onPressEnter={() => loadPendingShops()}
                    style={{ width: 250 }}
                  />
                  <Button onClick={() => loadPendingShops()}>搜索</Button>
                </Space>
              </Col>
              <Col>
                <Space>
                  <Button
                    type="primary"
                    icon={<CheckOutlined />}
                    disabled={state.selectedRowKeys.length === 0}
                    onClick={() => setState(prev => ({ ...prev, batchModalVisible: true }))}
                  >
                    批量审核
                  </Button>
                  <Button icon={<ExportOutlined />}>
                    导出数据
                  </Button>
                </Space>
              </Col>
            </Row>
          </Card>

          {/* 待审核商店表格 */}
          <Card>
            <Table
              columns={pendingColumns}
              dataSource={state.pendingShops}
              rowKey="_id"
              loading={state.pendingLoading}
              pagination={{
                current: state.pendingCurrent,
                pageSize: state.pendingPageSize,
                total: state.pendingTotal,
                showSizeChanger: true,
                showQuickJumper: true,
                showTotal: (total, range) =>
                  `第 ${range[0]}-${range[1]} 条，共 ${total} 条`,
              }}
              onChange={(pagination) => {
                loadPendingShops({
                  pendingCurrent: pagination.current,
                  pendingPageSize: pagination.pageSize,
                });
              }}
              rowSelection={{
                selectedRowKeys: state.selectedRowKeys,
                onChange: (selectedRowKeys) => {
                  setState(prev => ({ ...prev, selectedRowKeys }));
                }
              }}
            />
          </Card>
        </TabPane>

        <TabPane tab={<span><HistoryOutlined />审核历史</span>} key="history">
          {/* 筛选条件 */}
          <Card style={{ marginBottom: 16 }}>
            <Row gutter={16} align="middle">
              <Col>
                <Input
                  placeholder="搜索商店名称"
                  prefix={<SearchOutlined />}
                  value={state.keyword}
                  onChange={(e) => setState(prev => ({ ...prev, keyword: e.target.value }))}
                  style={{ width: 200 }}
                />
              </Col>
              <Col>
                <Select
                  placeholder="操作类型"
                  value={state.actionFilter}
                  onChange={(value) => setState(prev => ({ ...prev, actionFilter: value }))}
                  style={{ width: 120 }}
                  allowClear
                >
                  <Select.Option value="approved">审核通过</Select.Option>
                  <Select.Option value="rejected">审核拒绝</Select.Option>
                  <Select.Option value="suspended">暂停营业</Select.Option>
                  <Select.Option value="resumed">恢复营业</Select.Option>
                </Select>
              </Col>
              <Col>
                <RangePicker
                  value={state.dateRange}
                  onChange={(dates) => setState(prev => ({ ...prev, dateRange: dates }))}
                  placeholder={['开始日期', '结束日期']}
                />
              </Col>
              <Col>
                <Button onClick={() => loadApprovalHistory()}>搜索</Button>
              </Col>
            </Row>
          </Card>

          {/* 审核历史表格 */}
          <Card>
            <Table
              columns={[
                {
                  title: '商店名称',
                  dataIndex: 'shopName',
                  key: 'shopName',
                },
                {
                  title: '操作类型',
                  dataIndex: 'action',
                  key: 'action',
                  render: (action) => getActionTag(action),
                },
                {
                  title: '操作人',
                  dataIndex: 'operator',
                  key: 'operator',
                },
                {
                  title: '操作时间',
                  dataIndex: 'createdAt',
                  key: 'createdAt',
                  render: (date) => dayjs(date).format('YYYY-MM-DD HH:mm:ss'),
                },
                {
                  title: '状态变更',
                  key: 'statusChange',
                  render: (_, record) => (
                    <span>
                      {getStatusTag(record.previousStatus)} → {getStatusTag(record.newStatus)}
                    </span>
                  ),
                },
                {
                  title: '备注',
                  dataIndex: 'reason',
                  key: 'reason',
                  render: (reason) => reason || '-',
                },
              ]}
              dataSource={state.approvalHistory}
              rowKey="id"
              loading={state.historyLoading}
              pagination={{
                current: state.historyCurrent,
                pageSize: state.historyPageSize,
                total: state.historyTotal,
                showSizeChanger: true,
                showQuickJumper: true,
                showTotal: (total, range) =>
                  `第 ${range[0]}-${range[1]} 条，共 ${total} 条`,
              }}
              onChange={(pagination) => {
                loadApprovalHistory({
                  historyCurrent: pagination.current,
                  historyPageSize: pagination.pageSize,
                });
              }}
            />
          </Card>
        </TabPane>
      </Tabs>

      {/* 批量审核模态框 */}
      <Modal
        title="批量审核"
        open={state.batchModalVisible}
        onCancel={() => setState(prev => ({ ...prev, batchModalVisible: false }))}
        footer={null}
        width={500}
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={(values) => {
            handleBatchApproval(values.action, values.reason);
          }}
        >
          <Form.Item>
            <Text>已选中 {state.selectedRowKeys.length} 个商店</Text>
          </Form.Item>

          <Form.Item
            name="action"
            label="审核操作"
            rules={[{ required: true, message: '请选择审核操作' }]}
          >
            <Select placeholder="请选择操作">
              <Select.Option value="approved">审核通过</Select.Option>
              <Select.Option value="rejected">审核拒绝</Select.Option>
            </Select>
          </Form.Item>

          <Form.Item
            noStyle
            shouldUpdate={(prevValues, currentValues) =>
              prevValues.action !== currentValues.action
            }
          >
            {({ getFieldValue }) =>
              getFieldValue('action') === 'rejected' ? (
                <Form.Item
                  name="reason"
                  label="拒绝原因"
                  rules={[{ required: true, message: '请输入拒绝原因' }]}
                >
                  <TextArea rows={3} placeholder="请输入拒绝原因" />
                </Form.Item>
              ) : null
            }
          </Form.Item>

          <Form.Item>
            <Space>
              <Button type="primary" htmlType="submit">
                确认执行
              </Button>
              <Button onClick={() => setState(prev => ({ ...prev, batchModalVisible: false }))}>
                取消
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>

      {/* 商店详情模态框 */}
      <Modal
        title="商店详情"
        open={state.detailModalVisible}
        onCancel={() => setState(prev => ({ ...prev, detailModalVisible: false }))}
        footer={[
          <Button key="close" onClick={() => setState(prev => ({ ...prev, detailModalVisible: false }))}>
            关闭
          </Button>,
          state.selectedShop?.status === 'pending' && (
            <Button
              key="approve"
              type="primary"
              onClick={() => {
                if (state.selectedShop) {
                  handleSingleApproval(state.selectedShop._id, 'approved');
                  setState(prev => ({ ...prev, detailModalVisible: false }));
                }
              }}
            >
              审核通过
            </Button>
          ),
          state.selectedShop?.status === 'pending' && (
            <Button
              key="reject"
              danger
              onClick={() => {
                if (state.selectedShop) {
                  Modal.confirm({
                    title: '审核拒绝',
                    content: (
                      <Form>
                        <Form.Item label="拒绝原因" name="reason">
                          <TextArea rows={3} placeholder="请输入拒绝原因" />
                        </Form.Item>
                      </Form>
                    ),
                    onOk: (close) => {
                      const reason = form.getFieldValue('reason');
                      handleSingleApproval(state.selectedShop!._id, 'rejected', reason);
                      setState(prev => ({ ...prev, detailModalVisible: false }));
                      close();
                    },
                  });
                }
              }}
            >
              审核拒绝
            </Button>
          ),
        ].filter(Boolean)}
        width={800}
      >
        {state.selectedShop && (
          <Descriptions column={2} bordered>
            <Descriptions.Item label="商店名称" span={2}>
              {state.selectedShop.name}
            </Descriptions.Item>
            <Descriptions.Item label="商店类型">
              {state.selectedShop.type}
            </Descriptions.Item>
            <Descriptions.Item label="状态">
              {getStatusTag(state.selectedShop.status)}
            </Descriptions.Item>
            <Descriptions.Item label="店主">
              {state.selectedShop.owner?.name || 'N/A'}
            </Descriptions.Item>
            <Descriptions.Item label="联系电话">
              {state.selectedShop.contact?.phone || 'N/A'}
            </Descriptions.Item>
            <Descriptions.Item label="商店描述" span={2}>
              {state.selectedShop.description}
            </Descriptions.Item>
            <Descriptions.Item label="分类" span={2}>
              {state.selectedShop.categories?.join(', ') || 'N/A'}
            </Descriptions.Item>
            <Descriptions.Item label="申请时间" span={2}>
              {dayjs(state.selectedShop.createdAt).format('YYYY-MM-DD HH:mm:ss')}
            </Descriptions.Item>
          </Descriptions>
        )}
      </Modal>
    </div>
  );
};

export default ShopApproval;
